package com.lq.fastnews.utils;

import android.view.View;

import com.jakewharton.rxbinding.view.RxView;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Administrator on 2016/6/14.
 */
public class RxManager {
    private static RxManager mRxhHelper;
    private CompositeSubscription mSubscriptions;

    private RxManager(){

    }
    public static RxManager instance(){
        if(mRxhHelper==null){
            synchronized (RxManager.class){
                if(mRxhHelper==null)
                    mRxhHelper=new RxManager();

            }
        }
        return mRxhHelper;
    }
    public void add(Observable o, Subscriber subscriber){
        createSubscrib();
        mSubscriptions.add(o.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(subscriber));
    }
    public void add(Observable o, Action1 action1){
        createSubscrib();
        mSubscriptions.add(o.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(action1));
    }

    private void createSubscrib() {
        if (mSubscriptions == null || mSubscriptions.isUnsubscribed()) {
            mSubscriptions= new CompositeSubscription();
        }
    }

    public void fastClick(View view, Action1 action){
        createSubscrib();
        mSubscriptions.add(  RxView.clicks(view).throttleFirst(1000, TimeUnit.MILLISECONDS).subscribe(action));
    }
    public void unsubscribe(){
        if(mSubscriptions!=null){
            mSubscriptions.unsubscribe();
            mSubscriptions=null;
        }
    }

}
